package nckd.wnqjt.tmc.tda.plugin.form;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.Map;

public class FundaccountTaskPlugin  extends AbstractTask implements Plugin {

    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        QFilter accfilter = new QFilter("acctstatus", QCP.not_equals, "closed");
        // 获取指定或者当天日期的单据，有则更新，无则创建
        DynamicObject[] accountbanks = BusinessDataServiceHelper.load("bd_accountbanks","fundaccflag,nckd_fundaccount,acctstatus", null);
        for (DynamicObject accountbank : accountbanks) {
            // 判断账户是否出现在子账户中
            // 【集中资金账户标识】 如果本身有值，在子账户中新增了，那就不处理； 如果本身无值，在子账户中新增了，那就赋值  可归集；如果当前值= 可归集，并且在子账户中删掉了，那 当前值清空。如果当前值= 可归集以外的其他， 并且在子账户中删掉了，那不处理
            // 【是否资金集中账户】 有值无值都直接按逻辑处理
            QFilter filter = new QFilter("entrys.bankacct", QCP.equals, accountbank.getPkValue());
            DynamicObject[] acctgroups = BusinessDataServiceHelper.load("fca_acctgroup", "enable", filter.toArray());
            String fundaccflag = accountbank.getString("fundaccflag");
            String nckd_fundaccount = "1";
            if("closed".equals(accountbank.getString("acctstatus")) || acctgroups == null || acctgroups.length == 0){ // 如果银行账户已销户，则当做不存在子账户中逻辑处理
                fundaccflag = null;
            }else{
                for (DynamicObject acctgroup : acctgroups) {
                    if("1".equals(acctgroup.getString("enable"))){
                        if(fundaccflag == null || "".equals(fundaccflag)){
                            fundaccflag = "02";
                        }
                        nckd_fundaccount = "0";
                        break;
                    }else if("0".equals(acctgroup.getString("enable"))){
                        if("02".equals(fundaccflag)){
                            fundaccflag = null;
                        }
                        nckd_fundaccount = "1";
                    }
                }
            }
            accountbank.set("fundaccflag", fundaccflag);
            accountbank.set("nckd_fundaccount", nckd_fundaccount);
        }

        SaveServiceHelper.save(accountbanks);
    }


}
